﻿using System;
using System.Linq;
using System.Windows.Forms;
using NuSoft.SistemaGestionPersonal.WinFormsUI.BusinessEntities;

namespace NuSoft.SistemaGestionPersonal.WinFormsUI
{
    public partial class EmployeesForm : Form
    {
        private EmployeesFilterForm _employeesFilterForm;
        private FormClosingEventHandler _formClosing;

        public EmployeesForm(FormClosingEventHandler formClosing)
        {
            _formClosing = formClosing;

            InitializeComponent();
        }

        private void EmployeesForm_Load(object sender, EventArgs e)
        {
            
        }

        private void EmployeesForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var handler = _formClosing;

            if (handler != null)
            {
                handler(sender, e);
            }
        }

        private void NewEmployeeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var newUpdateEmployee = new NewUpdateEmployeeForm();

            if (newUpdateEmployee.ShowDialog(this) == DialogResult.OK)
            {
                Repository.Instance.Employees.Add(newUpdateEmployee.Employee);
                Repository.Instance.Persist();

                RefreshEmployees();
            }
        }

        private void UpdateEmployeeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (EmployeesListView.SelectedItems.Count == 1)
            {
                Employee employee = (Employee)EmployeesListView.SelectedItems[0].Tag;
                var newUpdateEmployee = new NewUpdateEmployeeForm(employee);

                if (newUpdateEmployee.ShowDialog(this) == DialogResult.OK)
                {
                    Repository.Instance.Employees.Remove(newUpdateEmployee.Employee);
                    Repository.Instance.Employees.Add(newUpdateEmployee.Employee);
                    Repository.Instance.Persist();

                    RefreshEmployees();
                }
            }
        }

        private void DeleteEmployeeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (EmployeesListView.SelectedItems.Count == 1)
            {
                Employee employee = (Employee)EmployeesListView.SelectedItems[0].Tag;
                if (MessageBox.Show(this, string.Format("¿Eliminar el operario \"{0} {1}\"?", employee.FirstName, employee.FirstSurname), MdiParent.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    Repository.Instance.Employees.Remove(employee);
                    Repository.Instance.Persist();

                    EmployeesListView.Items.Remove(EmployeesListView.SelectedItems[0]);
                }
            }
        }

        private void RemoveFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_employeesFilterForm != null)
            {
                RemoveFilterToolStripMenuItem.Enabled = false;

                _employeesFilterForm = new EmployeesFilterForm();
                RefreshEmployees();
            }
        }

        private void FilterSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_employeesFilterForm == null)
            {
                _employeesFilterForm = new EmployeesFilterForm();
            }

            if (_employeesFilterForm.ShowDialog(this) == DialogResult.OK)
            {
                RemoveFilterToolStripMenuItem.Enabled = _employeesFilterForm.EmployeeId.HasValue || !string.IsNullOrEmpty(_employeesFilterForm.EmployeeName) || !string.IsNullOrEmpty(_employeesFilterForm.EmployeeLastName);

                RefreshEmployees();
            }
        }

        private void EmployeesListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            UpdateEmployeeToolStripMenuItem.Enabled = DeleteEmployeeToolStripMenuItem.Enabled = EmployeesListView.SelectedItems.Count == 1;
        }

        public void RefreshEmployees()
        {
            EmployeesListView.Items.Clear();

            foreach (var employee in Repository.Instance.Employees.Where(employee => DoesEmployeeMatchCurrentFilter(employee)).OrderBy(employee => employee.Id))
            {
                var listViewItem = new ListViewItem { Tag = employee };
                listViewItem.Text = employee.Id.ToString();
                for (int i = 1; i < EmployeesListView.Columns.Count; i++)
                {
                    listViewItem.SubItems.Add(string.Empty);
                }
                listViewItem.SubItems[EntryDateColumnHeader.Index].Text = employee.EntryDate.ToShortDateString();
                listViewItem.SubItems[FirstNameColumnHeader.Index].Text = employee.FirstName;
                listViewItem.SubItems[MiddleNameColumnHeader.Index].Text = employee.MiddleName;
                listViewItem.SubItems[FirstSurnameColumnHeader.Index].Text = employee.FirstSurname;
                listViewItem.SubItems[SecondSurnameColumnHeader.Index].Text = employee.SecondSurname;
                listViewItem.SubItems[DocumentTypeColumnHeader.Index].Text = employee.DocumentType;
                listViewItem.SubItems[DocumentNumberColumnHeader.Index].Text = employee.DocumentNumber;
                listViewItem.SubItems[BirthDateColumnHeader.Index].Text = employee.BirthDate.ToShortDateString();
                listViewItem.SubItems[MaritalStatusColumnHeader.Index].Text = employee.MaritalStatus.ToLocalizedString();
                listViewItem.SubItems[PositionCategoryColumnHeader.Index].Text = employee.Position != null ? employee.Position.PositionCategory.ToLocalizedString() : string.Empty;
                listViewItem.SubItems[PositionColumnHeader.Index].Text = employee.Position != null ? employee.Position.Name : string.Empty;
                listViewItem.SubItems[FirstContactFirstNameColumnHeader.Index].Text = employee.FirstContactFirstName;
                listViewItem.SubItems[FirstContactSurnameColumnHeader.Index].Text = employee.FirstContactSurname;
                listViewItem.SubItems[FirstContactTelephoneNumberColumnHeader.Index].Text = employee.FirstContactTelephoneNumber;
                listViewItem.SubItems[FirstContactRelationshipColumnHeader.Index].Text = employee.FirstContactRelationship;

                EmployeesListView.Items.Add(listViewItem);
            }

            foreach (ColumnHeader columnHeader in EmployeesListView.Columns)
            {
                columnHeader.Width = -2;
            }
        }

        private bool DoesEmployeeMatchCurrentFilter(Employee employee)
        {
            bool result = true;

            int? id = _employeesFilterForm != null ? _employeesFilterForm.EmployeeId : null;
            string name = _employeesFilterForm != null ? _employeesFilterForm.EmployeeName : null;
            string lastName = _employeesFilterForm != null ? _employeesFilterForm.EmployeeLastName : null;

            if (id.HasValue)
            {
                result = employee.Id == id.Value;
            }
            if (result && !string.IsNullOrEmpty(name))
            {
                result = (!string.IsNullOrEmpty(employee.FirstName) && employee.FirstName.Contains(name, StringComparison.OrdinalIgnoreCase)) || (!string.IsNullOrEmpty(employee.MiddleName) && employee.MiddleName.Contains(name, StringComparison.OrdinalIgnoreCase));
            }
            if (result && !string.IsNullOrEmpty(lastName))
            {
                result = (!string.IsNullOrEmpty(employee.FirstSurname) && employee.FirstSurname.Contains(lastName, StringComparison.OrdinalIgnoreCase)) || (!string.IsNullOrEmpty(employee.SecondSurname) && employee.SecondSurname.Contains(lastName, StringComparison.OrdinalIgnoreCase));
            }

            return result;
        }
    }
}